from flask import Flask, request, jsonify, make_response
from werkzeug.security import generate_password_hash, check_password_hash
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS


app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = 'thisismysecretkey'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///login.db'

db = SQLAlchemy(app)


class Users(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True, nullable=False)
    password = db.Column(db.String(80), nullable=False)

    def __repr__(self):
        return f"User('{self.username}', '{self.password}')"


with app.app_context():
    db.create_all()


@app.route('/login', methods=['POST'])
def login():
    username = request.json['username']
    password = request.json['password']

    user = Users.query.filter_by(username=username).first()
    print(password)
    print(user.password)
    if user and password == user.password:
        print(f"用户名: {username}")
        response = make_response(jsonify({'message': 'Welcome to the login page!', 'code': 200,'success': True}))
        response.set_cookie('username', username, path='/', domain=None, httponly=True, secure=False)
        return response, 200
    else:
        return jsonify({'message': '账号密码错误!', 'code': 200, 'success': False}), 200


@app.route('/register', methods=['POST'])
def register():
    username = request.json['username']
    password = request.json['password']
    rePassword = request.json['rePassword']

    if not username or not password or not rePassword:
        return jsonify({"error": "所有字段都是必填的"}), 400
    if password != rePassword:
        return jsonify({'message': 'Passwords do not match!'})

    new_user = Users(username=username, password=password)
    db.session.add(new_user)
    db.session.commit()

    return jsonify({'message': 'User created successfully!'}), 200


@app.route('/logout', methods=['GET'])
def logout():
    response = make_response(jsonify({'message': 'Logout successfully!'}))
    response.delete_cookie('username')
    return response, 200


if __name__ == '__main__':
    app.run(debug=True)
